import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:my_salary/pages/todo/todo_vm.dart';
import 'package:provider/provider.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

import '../../api/models/todos_model.dart';

class TodoPage extends StatelessWidget {
  const TodoPage({super.key});

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => TodoViewModel()..fetchTodos(),
      child: const _TodoMainPageBody(),
    );
  }
}

class _TodoMainPageBody extends StatefulWidget {
  const _TodoMainPageBody();

  @override
  State<_TodoMainPageBody> createState() => _TodoMainPageState();
}

class _TodoMainPageState extends State<_TodoMainPageBody>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  late List<String> _tabs;

  CategoryOption _selectedCategory = CategoryOption.all;
  TodoSortField _sortField = TodoSortField.createTime;
  TodoSortOrder _sortOrder = TodoSortOrder.desc;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final l10n = AppLocalizations.of(context)!;
    _tabs = [l10n.todosTabUndo, l10n.todosTabCreated];
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    final vm = context.watch<TodoViewModel>();

    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.todosTitle),
        bottom: PreferredSize(
          preferredSize:  const Size.fromHeight(96),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TabBar(
                controller: _tabController,
                tabs: _tabs.map((t) => Tab(text: t)).toList(),
              ),
              _buildFilterBar(context),
            ],
          ),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: _tabs.map((tab) {
          return RefreshIndicator(
            onRefresh: () async {
              setState(() {
                vm.updateQuery(vm.query.copyWith(page: 1));
              });
            },
            child: _buildTodoList(context, tab),
          );
        }).toList(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _onAddTodo,
        child: const Icon(Icons.add),
      ),
    );
  }

  Widget _buildFilterBar(BuildContext context) {
    return Container(
      color: Theme.of(context).scaffoldBackgroundColor,
      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
      child: Row(
        children: [
          SizedBox(width: 12.w),
          // 分类选择
          InkWell(
            onTap: () => _onSelectCategory(context),
            child: Row(
              children: [
                Text(_categoryLabel(context, _selectedCategory)),
                const Icon(Icons.arrow_drop_down),
              ],
            ),
          ),
          SizedBox(width: 12.w),
          // 排序选择
          InkWell(
            onTap: () => _onSelectSort(context),
            child: Row(
              children: [
                Text(_sortFieldLabel(context, _sortField)),
                Icon(
                  _sortOrder == TodoSortOrder.asc
                      ? Icons.arrow_upward
                      : Icons.arrow_downward,
                  size: 16,
                ),
              ],
            ),
          ),
          const Spacer(),
          // 条件过滤
          IconButton(
            icon: const Icon(Icons.filter_list),
            onPressed: () => _onOpenFilterDialog(context),
          ),
        ],
      ),
    );
  }

  String _categoryLabel(BuildContext context, CategoryOption category) {
    final l10n = AppLocalizations.of(context)!;
    switch (category) {
      case CategoryOption.all:
        return l10n.todosCategoryAll;
      case CategoryOption.cx1104:
        return l10n.todosCategoryCx1104;
      case CategoryOption.cx1108:
        return l10n.todosCategoryCx1108;
    }
  }

  String _sortFieldLabel(BuildContext context, TodoSortField field) {
    final l10n = AppLocalizations.of(context)!;
    switch (field) {
      case TodoSortField.createTime:
        return l10n.todosSortCreateTime;
      case TodoSortField.handleTime:
        return l10n.todosSortHandleTime;
    }
  }

  Widget _buildTodoList(BuildContext context, String tab) {
    final vm = context.watch<TodoViewModel>();
    final l10n = AppLocalizations.of(context)!;

    final todos = vm.todos;
    if (todos.isEmpty) {
      return Center(
        child: Text(l10n.todosNoTodos,
            style: Theme.of(context).textTheme.bodyMedium),
      );
    }

    return NotificationListener<ScrollNotification>(
      onNotification: (scrollInfo) {
        if (scrollInfo.metrics.pixels >=
            scrollInfo.metrics.maxScrollExtent - 50) {
          // 距离底部 50px 时触发加载更多
          vm.loadMore();
        }
        return false;
      },
      child: ListView.builder(
        itemCount: vm.todos.length + (vm.hasMore ? 1 : 0),
        itemBuilder: (context, index) {
          if (index == vm.todos.length) {
            // 底部加载中占位
            return Padding(
              padding: EdgeInsets.all(16.r),
              child: const Center(child: CircularProgressIndicator()),
            );
          }
          final todo = vm.todos[index];
          return _buildTodoCard(todo);
        },
      ),
    );
  }

  Widget _buildTodoCard(TodoItemModel todo) {
    final tags = [todo.module, todo.excelNum];
    return Card(
      margin: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
      child: ListTile(
        title: Text(todo.itemName),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 原 subtitle
            Text(todo.itemContent),
            SizedBox(height: 4.h),
            // tags 区域
            Wrap(
              spacing: 6,
              runSpacing: -4,
              children: tags.map((tag) {
                return Container(
                  padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.05),
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: Text(
                    tag,
                    style: const TextStyle(fontSize: 10, color: Colors.blue),
                  ),
                );
              }).toList(),
            ),
          ],
        ),
        trailing: _setNodeName(todo.nodeName),
        onTap: () {
          // TODO: 跳转详情
        },
      ),
    );
  }

  Widget _setNodeName(String nodeName) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
      decoration: BoxDecoration(
        color: Colors.orange.withOpacity(0.1),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(nodeName,
          style: const TextStyle(color: Colors.orange, fontSize: 12)),
    );
  }

  Future<void> _onSelectCategory(BuildContext context) async {
    final l10n = AppLocalizations.of(context)!;
    final vm = context.read<TodoViewModel>();

    final categories = {
      CategoryOption.all: l10n.todosCategoryAll,
      CategoryOption.cx1104: l10n.todosCategoryCx1104,
      CategoryOption.cx1108: l10n.todosCategoryCx1108,
    };

    final selected = await showModalBottomSheet<CategoryOption>(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(12.r)),
      ),
      builder: (context) {
        return ListView(
          shrinkWrap: true,
          children: categories.entries.map((cat) {
            return ListTile(
              title: Text(cat.value),
              trailing: cat.key == _selectedCategory
                  ? const Icon(Icons.check, color: Colors.blue)
                  : null,
              onTap: () => Navigator.pop(context, cat.key),
            );
          }).toList(),
        );
      },
    );

    if (selected != null && selected != _selectedCategory) {
      setState(() {
        _selectedCategory = selected;
      });
      vm.updateQuery(vm.query.copyWith(categoryId: selected.label));
    }
  }

  Future<void> _onSelectSort(BuildContext context) async {
    final l10n = AppLocalizations.of(context)!;
    final vm = context.read<TodoViewModel>();

    final sortOptions = {
      TodoSortField.createTime: l10n.todosSortCreateTime,
      TodoSortField.handleTime: l10n.todosSortHandleTime,
    };

    final result = await showModalBottomSheet<Map<String, dynamic>>(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(12.r)),
      ),
      builder: (context) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: sortOptions.entries.map((entry) {
            return ListTile(
              title: Text(entry.value),
              trailing: _sortField == entry.key
                  ? Icon(
                      _sortOrder == TodoSortOrder.asc
                          ? Icons.arrow_upward
                          : Icons.arrow_downward,
                      color: Colors.blue,
                    )
                  : null,
              onTap: () {
                Navigator.pop(context, {
                  'field': entry.key,
                  'order': _sortField == entry.key &&
                          _sortOrder == TodoSortOrder.desc
                      ? TodoSortOrder.asc
                      : TodoSortOrder.desc,
                });
              },
            );
          }).toList(),
        );
      },
    );

    if (result != null) {
      setState(() {
        _sortField = result['field'] as TodoSortField;
        _sortOrder = result['order'] as TodoSortOrder;
      });
      vm.updateQuery(vm.query.copyWith(
        sortField: _sortField,
        sortOrder: _sortOrder,
        page: 1,
      ));
    }
  }

  Future<void> _onOpenFilterDialog(BuildContext context) async {
    final vm = context.read<TodoViewModel>();
    final l10n = AppLocalizations.of(context)!;

    TodoFilterModel tempFilter = vm.filter;

    final confirmed = await showModalBottomSheet<bool>(
      context: context,
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(12.r)),
      ),
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setModalState) {
            return Padding(
              padding: EdgeInsets.all(16.r),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 状态选择
                  Row(
                    children: [
                      Text("${l10n.todosFilterStatus}:"),
                      SizedBox(width: 8.w),
                      ChoiceChip(
                        label: Text(l10n.todosFilterStatusAll),
                        selected: tempFilter.status == TodoFilterStatus.all,
                        onSelected: (_) => setModalState(() => tempFilter =
                            tempFilter.copyWith(status: TodoFilterStatus.all)),
                      ),
                      SizedBox(width: 8.w),
                      ChoiceChip(
                        label: Text(l10n.todosFilterStatusPending),
                        selected: tempFilter.status == TodoFilterStatus.pending,
                        onSelected: (_) => setModalState(() => tempFilter =
                            tempFilter.copyWith(
                                status: TodoFilterStatus.pending)),
                      ),
                      SizedBox(width: 8.w),
                      ChoiceChip(
                        label: Text(l10n.todosFilterStatusComplete),
                        selected:
                            tempFilter.status == TodoFilterStatus.completed,
                        onSelected: (_) => setModalState(() => tempFilter =
                            tempFilter.copyWith(
                                status: TodoFilterStatus.completed)),
                      ),
                    ],
                  ),
                  SizedBox(height: 16.h),
                  // 日期范围
                  Row(
                    children: [
                      Text("${l10n.todosFilterStartTime}:"),
                      TextButton(
                        onPressed: () async {
                          final date = await showDatePicker(
                            context: context,
                            initialDate: DateTime.now(),
                            firstDate: DateTime(2020),
                            lastDate: DateTime(2100),
                          );
                          if (date != null) {
                            setModalState(() => tempFilter =
                                tempFilter.copyWith(startDate: date));
                          }
                        },
                        child: Text(
                            tempFilter.startDate?.toString().split(' ')[0] ??
                                l10n.commonChoose),
                      ),
                      SizedBox(width: 8.w),
                      Text("${l10n.todosFilterEndTime}:"),
                      TextButton(
                        onPressed: () async {
                          final date = await showDatePicker(
                            context: context,
                            initialDate: DateTime.now(),
                            firstDate: DateTime(2020),
                            lastDate: DateTime(2100),
                          );
                          if (date != null) {
                            setModalState(() => tempFilter =
                                tempFilter.copyWith(endDate: date));
                          }
                        },
                        child: Text(
                            tempFilter.endDate?.toString().split(' ')[0] ??
                                l10n.commonChoose),
                      ),
                    ],
                  ),
                  SizedBox(height: 24.h),
                  Row(
                    children: [
                      Expanded(
                        child: OutlinedButton(
                          onPressed: () {
                            tempFilter = TodoFilterModel();
                            setModalState(() {});
                          },
                          child: Text(l10n.commonRest),
                        ),
                      ),
                      SizedBox(width: 12.h),
                      Expanded(
                        child: ElevatedButton(
                          onPressed: () => Navigator.pop(context, true),
                          child: Text(l10n.commonConfirm),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            );
          },
        );
      },
    );

    if (confirmed == true) {
      vm.updateFilter(tempFilter);
    }
  }

  void _onAddTodo() async {
    // 这里可以直接跳转到创建待办页面

    // if (created == true) {
    //   // TODO: 刷新列表
    // }
  }
}
